//! 应用运行时模块
//! 
//! 提供应用运行时的管理和控制功能

use crate::utils::error::{YayaError, Result};

/// 应用运行时配置
#[derive(Debug, Clone)]
pub struct RuntimeConfig {
    pub stack_size: usize,
    pub heap_size: usize,
    pub enable_networking: bool,
    pub enable_filesystem: bool,
    pub enable_graphics: bool,
}

/// 应用运行时
pub struct YayaRuntime {
    config: RuntimeConfig,
    initialized: bool,
}

impl YayaRuntime {
    /// 创建新的应用运行时
    pub fn new() -> Result<Self, YayaError> {
        let config = RuntimeConfig {
            stack_size: 1024 * 1024, // 1MB栈大小
            heap_size: 64 * 1024 * 1024, // 64MB堆大小
            enable_networking: true,
            enable_filesystem: true,
            enable_graphics: false,
        };
        
        Ok(YayaRuntime {
            config,
            initialized: false,
        })
    }
    
    /// 初始化应用运行时
    pub fn init() -> Result<(), YayaError> {
        info!("初始化应用运行时");
        Ok(())
    }
    
    /// 关闭应用运行时
    pub fn shutdown() -> Result<(), YayaError> {
        info!("关闭应用运行时");
        Ok(())
    }
    
    /// 启动应用
    pub fn run<F>(&mut self, app_main: F) -> Result<(), YayaError> 
    where
        F: FnOnce() -> Result<(), YayaError>,
    {
        if !self.initialized {
            self.initialize_runtime()?;
        }
        
        info!("启动应用");
        
        // 执行应用主函数
        match app_main() {
            Ok(()) => {
                info!("应用正常退出");
                Ok(())
            }
            Err(e) => {
                error!("应用异常退出: {:?}", e);
                Err(e)
            }
        }
    }
    
    /// 配置运行时参数
    pub fn configure(&mut self, config: RuntimeConfig) -> Result<(), YayaError> {
        self.config = config;
        Ok(())
    }
    
    /// 获取运行时配置
    pub fn get_config(&self) -> &RuntimeConfig {
        &self.config
    }
    
    fn initialize_runtime(&mut self) -> Result<(), YayaError> {
        info!("初始化运行时环境");
        
        // 初始化硬件抽象层
        crate::hal::cpu::init()?;
        crate::hal::memory::init()?;
        crate::hal::interrupts::init()?;
        crate::hal::devices::init()?;
        
        // 初始化系统服务
        crate::services::scheduler::init()?;
        crate::services::allocator::init()?;
        
        if self.config.enable_filesystem {
            crate::services::fs::init()?;
        }
        
        if self.config.enable_networking {
            crate::services::network::init()?;
        }
        
        self.initialized = true;
        Ok(())
    }
}